/* Copyright (C) 2003-2012 Free Software Foundation, Inc.
   This file is part of the GNU C Library.
   Contributed by Martin Schwidefsky <schwidefsky@de.ibm.com>, 2003.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <http://www.gnu.org/licenses/>.  */

#include <errno.h>
#include <sysdep.h>
#include <lowlevellock.h>
#include <pthread.h>
#include <pthreadP.h>
#include <stap-probe.h>

/*
 * 从下面的解锁流程可以看出，写者优先也存在自私的倾向，因为写锁解锁的时候，首先会去查找有没有阻塞的写锁请求，如果有，先唤醒写锁请求线程。因此如果当前读写锁状态是写锁，同时到来很多写请求和读请求，那它将总是优先处理写请求。如果写锁请求源源不断地到来，那它一样会将读锁请求饿死。
 * 如果是读锁解锁不会把其余读锁饿死，因为读锁之间是共享的。
 */
/* Unlock RWLOCK.  */
int
__pthread_rwlock_unlock (pthread_rwlock_t *rwlock)
{
  LIBC_PROBE (rwlock_unlock, 1, rwlock);
   
  // 无论是申请读锁还是申请写锁，还是解锁，都至少会做一次全局互斥锁（对应__lock）的加锁和解锁，若不考虑阻塞，单单考虑操作本身的开销，读写锁的加解锁开销是互斥锁的两倍。
  lll_lock (rwlock->__data.__lock, rwlock->__data.__shared);
  
  // 如果当前是写锁，执行__writer = 0，表示释放写锁。
  if (rwlock->__data.__writer)
    rwlock->__data.__writer = 0;
  else // 如果当前是读锁，则执行__nr_readers--，表示读锁占有者少了一个。 
    --rwlock->__data.__nr_readers;
  
  // 判断__nr_readers是否等于0，如果是则表示自己是最后一个读锁占有者，需要唤醒依次尝试唤醒写锁等待者和所有的读锁等待者。
  if (rwlock->__data.__nr_readers == 0)
    {
      // 根据__nr_writers_queued判断有没有写锁等待者，如果有，则唤醒一个写锁等待者。
      if (rwlock->__data.__nr_writers_queued)
	{
	  ++rwlock->__data.__writer_wakeup;
	  lll_unlock (rwlock->__data.__lock, rwlock->__data.__shared);
	  lll_futex_wake (&rwlock->__data.__writer_wakeup, 1,
			  rwlock->__data.__shared);
	  return 0;
	}
      // 如果没有写锁等待者，则判断有没有读锁等待者，如果有，则将所有的读锁等待者一起唤醒。
      else if (rwlock->__data.__nr_readers_queued)
	{
	  ++rwlock->__data.__readers_wakeup;
	  lll_unlock (rwlock->__data.__lock, rwlock->__data.__shared);
	  lll_futex_wake (&rwlock->__data.__readers_wakeup, INT_MAX,
			  rwlock->__data.__shared);
	  return 0;
	}
    }
  lll_unlock (rwlock->__data.__lock, rwlock->__data.__shared);
  return 0;
}

weak_alias (__pthread_rwlock_unlock, pthread_rwlock_unlock)
hidden_def (__pthread_rwlock_unlock)
